package com.alone.openai.api;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import com.alone.openai.api.core.Api;
import com.alone.openai.api.core.GlobalProperties;
import com.alone.openai.api.core.param.CompletionParam;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;

import java.util.Objects;
import java.util.Scanner;
import java.util.function.Consumer;


/**
 * 快速开始
 *
 * @author Alone
 * @date 2023/3/22 10:01 上午
 */
public class Test {

    public static void main(String[] args) {
        closeLog();
        // 在application.yml中设置你的api-key
        String token = GlobalProperties.getToken();
        System.out.println("token: " + token);
        runTerminalInteract("请输入: ",
                msg -> {
                    // 构建请求内容
                    CompletionParam param = CompletionParam.of(msg);
                    // 发起请求
                    String response = Api.COMPLETIONS_V1.customize()
                            .removeHeader(HttpHeaders.AUTHORIZATION)
                            .header(HttpHeaders.AUTHORIZATION, token)
                            .build()
                            .exec(param).getContent();
                    System.out.println("ChatGpt: " + response);
                });
    }

    private static void closeLog() {
        ((LoggerContext) LoggerFactory.getILoggerFactory())
                .getLogger(Logger.ROOT_LOGGER_NAME)
                .detachAndStopAllAppenders();
    }

    private static void runTerminalInteract(String tips, Consumer<String> msgConsumer) {
        Scanner scanner = new Scanner(System.in);
        System.out.print(tips);
        while (scanner.hasNextLine()) {
            String msg = scanner.nextLine();
            if (Objects.equals(msg, "exit")) {
                System.exit(0);
            }
            msgConsumer.accept(msg);
            System.out.print(tips);
        }
    }


}
